import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/util/ImConstant.dart';

import '../../pojo/ImPojo.dart';
import '../bloc/CollectListCubit.dart';
import '../view/component/cell/CollectItemView.dart';

/// 收藏页面
class ImCollectListPage extends StatefulWidget {
  const ImCollectListPage({super.key});

  @override
  State<StatefulWidget> createState() => _ImCollectState();
}

class _ImCollectState extends State<ImCollectListPage> with TickerProviderStateMixin {
  double _position = -350;

  final _userFocusNode = FocusNode();
  late AnimationController _animatedContainer;
  late Animation<double> _animation;
  late TextEditingController _textEditingController;

  @override
  void initState() {
    super.initState();

    _animatedContainer = AnimationController(duration: const Duration(milliseconds: 300), vsync: this);
    _animation =
        Tween<double>(begin: _position, end: 0).animate(CurvedAnimation(parent: _animatedContainer, curve: Curves.easeIn));

    var collectListCubit = context.read<CollectListCubit>();
    collectListCubit.add(CollectListLoadEvent());
    _userFocusNode.addListener(() {
      if (collectListCubit.state.search == '' && !_userFocusNode.hasFocus) {
        collectListCubit.add(CollectListSearchableEvent(false));
      }
    });

    _textEditingController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    var collectListCubit = context.watch<CollectListCubit>();
    return Scaffold(
      appBar: _buildAppBar(context),
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      body: Column(
        children: [
          _buildSearchPane(context),
          Expanded(
              child: ClipRRect(
            child: Stack(
              children: [
                Column(
                  children: [
                    _buildTab(collectListCubit),            // 筛选tab
                    _buildCollectPane(collectListCubit),    // 收藏列表
                  ],
                ),
                _buildCollapse(context),
              ],
            ),
          ))
        ],
      ),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      leading: GestureDetector(
        onTap: () {
          Navigator.of(context).pop();
        },
        child: const Icon(Icons.chevron_left),
      ),
      title: const Text('我的收藏'),
      centerTitle: true,
      actions: [
        IconButton(
          icon: const Icon(
            Icons.add_circle_outline,
            color: ImConstant.IM_TEXT_COLOR,
          ),
          tooltip: '',
          onPressed: () {},
        )
      ],
    );
  }

  Widget _buildSearchPane(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 5, right: 5, bottom: 5),
      height: 30,
      decoration: const BoxDecoration(
        color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
        borderRadius: BorderRadius.all(Radius.circular(5)),
      ),
      child: _buildSearchContent(context),
    );
  }

  Widget _buildSearchContent(BuildContext context) {
    var collectListCubit = context.watch<CollectListCubit>();
    if (collectListCubit.state.searchable || collectListCubit.state.prefix != '') {
      return SizedBox(
        height: 30,
        child: Row(children: [
          if (collectListCubit.state.prefix != '') _buildPrefix(collectListCubit),
          Expanded(child: TextField(
            focusNode: _userFocusNode,
            controller: _textEditingController,
            decoration: InputDecoration(
                border: const OutlineInputBorder(gapPadding: 1, borderRadius: BorderRadius.all(Radius.circular(5))),
                fillColor: Colors.white,
                isCollapsed: true,
                filled: true,
                hintMaxLines: 100,
                contentPadding: const EdgeInsets.only(top: 5, right: 5, bottom: 5, left: 5),
                enabledBorder: OutlineInputBorder(
                  gapPadding: 4,
                  borderRadius: BorderRadius.circular(5.0),
                  borderSide: const BorderSide(
                    color: Colors.white,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  //选中时外边框颜色
                  gapPadding: 4,
                  borderRadius: BorderRadius.circular(5.0),
                  borderSide: const BorderSide(
                    color: Colors.white,
                  ),
                ),
                suffixIcon: collectListCubit.state.search != '' ? IconButton(
                  color: ImConstant.IM_LOGIN_DEFAULT_COLOR,
                  icon: const Icon(Icons.highlight_remove_sharp, size: 18,),
                  onPressed: () {
                    _textEditingController.text = '';
                    collectListCubit.add(CollectListCleanSearchEvent());
                  },
              )
                  : null,
            ),

            cursorHeight: 22,
            autocorrect: true,
            autofocus: false,
            textAlign: TextAlign.left,
            style: const TextStyle(fontSize: 18.0, color: Colors.black),
            onChanged: (text) {
              collectListCubit.add(CollectListSearchKeyEvent(text));
              delayedSubmit(collectListCubit, text);
            },
            enabled: true, //是否禁用
          ))
        ],),
      );
    } else {
      return GestureDetector(
        onTap: () {
          collectListCubit.add(CollectListSearchableEvent(true));
          _userFocusNode.requestFocus();
        },
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Padding(
              padding: EdgeInsets.only(right: 10, left: 20),
              child: Icon(Icons.search),
            ),
            Padding(
              padding: EdgeInsets.only(right: 20),
              child: Text('搜索'),
            ),
          ],
        ),
      );
    }
  }

  Widget _buildTab(CollectListCubit collectListCubit) {
    return Container(
      margin: const EdgeInsets.only(top: 5, bottom: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 10),
            child: _buildTabText(collectListCubit, '所有', [], 40),
          ),
          _buildTabText(collectListCubit, '图片与视频', [ImMessageType.Image, ImMessageType.Video], 80),
          _buildTabText(collectListCubit, '文件', [ImMessageType.File], 40),
          _buildTabText(collectListCubit, '链接', [ImMessageType.Url], 60),
          Expanded(child: Align(
            alignment: Alignment.centerRight,
            child: Padding(padding: const EdgeInsets.only(right: 20), child: _buildCollectIcon(context),),
          ))
        ],
      ),
    );
  }

  Widget _buildCollectPane(CollectListCubit collectListCubit) {
    return Expanded(
        child: Container(
          color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
          child: ListView.builder(itemBuilder: (BuildContext context, int index) {
            var collect = collectListCubit.state.collects[index];
            return Container(
              margin: const EdgeInsets.only(top: 10, bottom: 10, left: 5, right: 5),
              decoration: const BoxDecoration(color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
                  borderRadius: BorderRadius.all(Radius.circular(10))
              ),
              child: CollectItemView(collect: collect,),
            );
          }, itemCount: collectListCubit.state.collects.length,),
        )
    );
  }

  Widget _buildTabText(CollectListCubit collectListCubit, String title, List<ImMessageType> messageTypes,
      [double? width = 100]) {
    bool isSelect = collectListCubit.state.prefix == title;
    return GestureDetector(
      onTap: () {
        collectListCubit.add(CollectListMessageTypeEvent(title, messageTypes));
      },
      child: SizedBox(
        width: width,
        child: Text(
          title,
          style: TextStyle(color: Colors.lightBlueAccent,
              fontWeight: isSelect ? FontWeight.w800 : FontWeight.w200),
        ),
      ),
    );
  }

  Widget _buildCollectIcon(BuildContext context) {
    var collectListCubit = context.watch<CollectListCubit>();
    if (!collectListCubit.state.collectable && _animatedContainer.isForwardOrCompleted) {
      _animatedContainer.reverse();
    }
    if (collectListCubit.state.searchable) {
      return GestureDetector(
        onTap: () {
          _animatedContainer.reverse();
          collectListCubit.add(CollectListCollectableEvent(false));
        },
        child: const Icon(Icons.keyboard_arrow_up),
      );
    }
    return GestureDetector(
      onTap: () {
        _animatedContainer.forward();
        collectListCubit.add(CollectListCollectableEvent(true));
      },
      child: const Icon(Icons.keyboard_arrow_down),
    );
  }

  Widget _buildCollapse(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (BuildContext context, Widget? child) {
        return Transform.translate(
            offset: Offset(0, _animation.value),
            child: Container(
              height: 300,
              decoration: BoxDecoration(
                  color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
                  borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(15),
                      bottomRight: Radius.circular(15))),
              margin: const EdgeInsets.only(top: 10),
              // color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
              child: _buildCollapseContent(context),
            ));
      },
    );
  }

  Widget _buildCollapseContent(BuildContext context) {
    var collectListCubit = context.read<CollectListCubit>();

    return Column(
      children: [
        Container(
          margin: const EdgeInsets.only(top: 10, bottom: 10),
          child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const Icon(Icons.list_rounded),
                const Text('类型'),
                Expanded(child: Align(
                  alignment: Alignment.centerRight,
                  child: Padding(padding: const EdgeInsets.only(right: 20), child: GestureDetector(
                    onTap: () {
                      _animatedContainer.reverse();
                      collectListCubit.add(CollectListCollectableEvent(false));
                    },
                    child: const Icon(Icons.keyboard_arrow_up),
                  ),),
                )),
              ]
          ),
        ),
        Container(
          constraints: const BoxConstraints(maxHeight: 160),
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: GridView(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3, childAspectRatio: 3, mainAxisSpacing: 10, crossAxisSpacing: 10),
            children: [
              _buildCollectItem(collectListCubit, '所有',  []),
              _buildCollectItem(collectListCubit, '图片与视频', [ImMessageType.Image, ImMessageType.Video]),
              _buildCollectItem(collectListCubit, '文件', [ImMessageType.File]),
              _buildCollectItem(collectListCubit, '链接', [ImMessageType.Url]),
              _buildCollectItem(collectListCubit, '聊天记录', [ImMessageType.Text, ImMessageType.RichText]),
              _buildCollectItem(collectListCubit, '笔记', []),
              _buildCollectItem(collectListCubit, '小程序', []),
              _buildCollectItem(collectListCubit, '语音', [ImMessageType.Audio]),
            ],
          ),
        ),
        const Row(
          children: [
            Icon(Icons.label_important_outline),
            Text('标签'),
          ],
        ),
      ],
    );
  }

  Widget _buildCollectItem(CollectListCubit collectListCubit, String title, List<ImMessageType> messageTypes) {
    bool isSelect = collectListCubit.state.prefix == title;
    return GestureDetector(
      onTap: () {
        collectListCubit.add(CollectListMessageTypeEvent(title, messageTypes));
      },
      child: Container(
        color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
        child: Center(
          child: Text(title, style: TextStyle(fontWeight: isSelect ? FontWeight.w500 : FontWeight.w200),),
        ),
      ),
    );
  }

  Widget _buildPrefix(CollectListCubit collectListCubit) {
    return GestureDetector(
      onTap: () {
        collectListCubit.add(CollectListMessageTypeEvent('', []));
      },
      child: Container(
        height: 25,
        decoration: BoxDecoration(color: ImConstant.IM_MAIN_BACKGROUND_COLOR, borderRadius: BorderRadius.all(Radius.circular(5))),
        padding: const EdgeInsets.only(left: 5, top: 2, bottom: 2, right: 5),
        margin: const EdgeInsets.only(left: 5),
        child: Text(collectListCubit.state.prefix),
      ),
    );
  }

  void delayedSubmit(CollectListCubit collectListCubit, String search) {
    Future.delayed(const Duration(milliseconds: 500), () {
      if (search == collectListCubit.state.search) {
        collectListCubit.add(CollectListSearchEvent(search));
      }
    });
  }

  @override
  void dispose() {
    _userFocusNode.dispose();
    _animatedContainer.dispose();
    super.dispose();
  }
}
